package com.app.controller;

import com.alibaba.fastjson.JSONObject;
import com.app.common.SystemConstant;
import com.app.enums.StatusCodeEnum;
import com.app.result.CommonResult;
import com.app.util.FileTypeCheckerUtil;
import com.app.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.regex.Pattern;

@Controller
@RestController
@RequestMapping("/file")
@Api(tags = "文件相关接口")
public class UploadController {

    private static final Pattern VALID_FILENAME_PATTERN = Pattern.compile("^[a-zA-Z0-9_.-]+$");

    @Autowired
    private FileTypeCheckerUtil fileTypeCheckerUtil;

    /**
     * 上传图片
     */
    @ApiOperation("上传图片")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "图片文件", required = true, dataType = "MultipartFile"),
    })
    @PostMapping("/upload")
    public CommonResult<?> upload(@RequestParam("file") MultipartFile file, String fileType) throws IOException {
        if (!FileTypeCheckerUtil.isAllowedFileType(file)) {
            return CommonResult.failed("文件类型错误!");
        }
        //防止路径遍历
        String originalFileName = file.getOriginalFilename();
        if (!StringUtils.hasText(originalFileName) || !VALID_FILENAME_PATTERN.matcher(originalFileName).matches()) {
            return CommonResult.failed("文件名不合法!");
        }

        // 定义文件存储的基础路径
        String basePath = SystemConstant.DEFAULT_UPLOAD_URL;

        // 获取当前日期并格式化
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        String datePath = sdf.format(new Date());

        // 构建完整的存储路径
        String filePathStr = basePath + datePath + "/";

        File filePath = new File(filePathStr);

        // 如果目录不存在，创建目录
        if (!filePath.exists()) {
            filePath.mkdirs();
        }

        // 获得上传文件名
        String fileName = file.getOriginalFilename();
        assert fileName != null;
        int lastIndexOf = fileName.lastIndexOf(".");
        String date = getRandomString2(8);
        // 获取文件的后缀名.jpg
        String suffix = fileName.substring(lastIndexOf);
        filePath = new File(filePathStr + date + suffix);


//        if (fileType != null && !fileType.isEmpty()) {
//            if ("1".equals(fileType)) {
//                if (!FileTypeCheckerUtil.isPictureFileType(file)) {
//                    return CommonResult.failed("图片类型错误!");
//                }
//            } else {
//                if (!FileTypeCheckerUtil.isFileType(file)) {
//                    return CommonResult.failed("文件类型错误!");
//                }
//            }
//        }
        // 将上传文件保存到目标文件中
        file.transferTo(filePath);
        JSONObject object = new JSONObject();
        int file_Type = 2;
        if (suffix.equals(".jpg") || suffix.equals(".png") || suffix.equals(".jpeg") || suffix.equals(".gif") || suffix.equals(".bmp")) {
            file_Type = 1;
        }
        object.put("url", "/file/" + datePath + "/" + date + suffix);
        object.put("name", fileName);
        object.put("size", FileUtils.byteCountToDisplaySize(filePath.length()));
        object.put("type", file_Type);
        object.put("filetype", suffix);
        return CommonResult.success(object);
    }

    //删除对象
    @ApiOperation(value = "删除图片")
    @GetMapping("/deleteObject")
    public CommonResult<Object> deleteObject(String filename) {
        // 从返回值中提取实际的文件路径
        String filePath = filename.replaceFirst("/file/", "");

        File file = new File(SystemConstant.DEFAULT_UPLOAD_URL + filePath);
        if (file.exists()) {
            if (file.delete()) {
                return CommonResult.success("图片删除成功");
            } else {
                return CommonResult.failed("图片删除失败");
            }
        } else {
            return CommonResult.failed("图片不存在，无法删除");
        }
    }


    //可以指定字符串的某个位置是什么范围的值
    public static String getRandomString2(int length) {
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(3);
            long result = 0;
            switch (number) {
                case 0:
                    result = Math.round(Math.random() * 25 + 65);
                    sb.append(String.valueOf((char) result));
                    break;
                case 1:
                    result = Math.round(Math.random() * 25 + 97);
                    sb.append(String.valueOf((char) result));
                    break;
                case 2:
                    sb.append(String.valueOf(new Random().nextInt(10)));
                    break;
            }
        }
        return sb.toString();
    }
}
